// import {  } from '@/api/user'
import { login,logout } from '@/api/api'
import { getToken, setToken, removeToken,getroless,setroless} from '@/utils/auth'
import {resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    names: '',
    avatar: '',
	  roles:'',
    roless:'',

  }
}
function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}


const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NAMES: (state, names) => {
    state.names = names
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
  ,
  SET_ROLESS: (state, roless) => {
    state.roless = roless
  }

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        console.log(response,'66');
        commit('SET_TOKEN', response.token)
        commit('SET_NAMES', response.name)
        commit('SET_ROLESS', response.privilege)
        setToken(response.token)
        setroless(response.privilege)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
     
      // getInfo(state.token).then(response => {
      //   const { data } = response
      //   if (!data) {
      //     return reject('Verification failed, please Login again.')
      //   }
      //   const { name, avatar ,roles } = data
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   commit('SET_ROLES', roles)
      let oneroless =  getroless()?getroless():this.state.user.roless
      commit('SET_NAME', this.state.user.names)
      commit('SET_ROLES', oneroless)
      //setroless(oneroless)
      resolve(oneroless)
      // }).catch(error => {
      //   reject(error)
      // })
    })
   
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
